package com.bourne.interceptor;

import com.bourne.constant.StringConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

public class LogsInterceptor implements HandlerInterceptor {

    private static final Logger log = LoggerFactory.getLogger(LogsInterceptor.class);

//    clear() => 移除所有MDC
//    get (String key) => 获取当前线程MDC中指定key的值
//    getContext() => 获取当前线程MDC的MDC
//    put(String key, Object o) => 往当前线程的MDC中存入指定的键值对
//    remove(String key) => 删除当前线程MDC中指定的键值对
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse response, Object handler) throws Exception {
        String xForwardedForHeader = httpServletRequest.getHeader( "X-Forwarded-For");
        String remoteIp = httpServletRequest.getRemoteAddr();
        String uuid = UUID.randomUUID().toString();
        log.info( "request id:{}, client ip:{}, X-Forwarded-For:{}", uuid, remoteIp, xForwardedForHeader);
        MDC.put(StringConstant.REQUEST_ID, uuid);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        MDC.remove(StringConstant.REQUEST_ID);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
